package com.luo.backend.service;

import com.luo.backend.dto.AdminMerchantDetailResponse;
import com.luo.backend.dto.AdminMerchantListResponse;
import com.luo.backend.entity.Food;
import com.luo.backend.entity.Merchant;
import com.luo.backend.entity.Order;
import com.luo.backend.entity.User;
import com.luo.backend.repository.FoodRepository;
import com.luo.backend.repository.MerchantRepository;
import com.luo.backend.repository.OrderRepository;
import com.luo.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 管理员-商家管理服务
 */
@Service
public class AdminMerchantService {
    
    @Autowired
    private MerchantRepository merchantRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    /**
     * 获取商家列表
     */
    public AdminMerchantListResponse getMerchantList(
            Integer page,
            Integer size,
            String keyword,
            Integer status,
            String sortBy,
            String sortOrder) {
        
        // 设置默认值
        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;
        if (sortBy == null) sortBy = "createdAt";
        if (sortOrder == null) sortOrder = "desc";
        
        // 创建分页和排序
        Sort sort = sortOrder.equalsIgnoreCase("asc") ? 
                    Sort.by(sortBy).ascending() : 
                    Sort.by(sortBy).descending();
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        
        // 构建查询条件
        Specification<Merchant> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                String likePattern = "%" + keyword + "%";
                predicates.add(cb.or(
                    cb.like(root.get("name"), likePattern),
                    cb.like(root.get("phone"), likePattern),
                    cb.like(root.get("address"), likePattern)
                ));
            }
            
            // 状态筛选
            if (status != null) {
                predicates.add(cb.equal(root.get("status"), status));
            }
            
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        
        // 查询数据
        Page<Merchant> merchantPage = merchantRepository.findAll(spec, pageable);
        
        // 构建响应
        AdminMerchantListResponse response = new AdminMerchantListResponse();
        
        // 设置商家列表
        List<AdminMerchantListResponse.MerchantItem> items = merchantPage.getContent().stream()
            .map(this::convertToMerchantItem)
            .collect(Collectors.toList());
        response.setItems(items);
        
        // 设置分页信息
        response.setPagination(new AdminMerchantListResponse.Pagination(
            page, 
            size, 
            merchantPage.getTotalElements()
        ));
        
        // 设置统计信息
        response.setStatistics(getMerchantStatistics());
        
        return response;
    }
    
    /**
     * 获取商家详情
     */
    public AdminMerchantDetailResponse getMerchantDetail(Long merchantId) {
        Optional<Merchant> merchantOpt = merchantRepository.findById(merchantId);
        if (!merchantOpt.isPresent()) {
            throw new RuntimeException("商家不存在");
        }
        
        Merchant merchant = merchantOpt.get();
        AdminMerchantDetailResponse response = new AdminMerchantDetailResponse();
        
        // 基本信息
        response.setId(merchant.getId());
        response.setName(merchant.getName());
        response.setDescription(merchant.getDescription());
        response.setLogo(merchant.getLogo());
        response.setPhone(merchant.getPhone());
        response.setAddress(merchant.getAddress());
        response.setBusinessHours(merchant.getBusinessHours());
        response.setMinOrderAmount(merchant.getMinOrderAmount());
        response.setDeliveryFee(merchant.getDeliveryFee());
        response.setRating(merchant.getRating());
        response.setRatingCount(merchant.getRatingCount());
        response.setStatus(merchant.getStatus());
        response.setStatusText(merchant.getStatus() == 1 ? "营业中" : "休息中");
        response.setOwnerUserId(merchant.getOwnerUserId());
        response.setCreatedAt(merchant.getCreatedAt());
        response.setUpdatedAt(merchant.getUpdatedAt());
        
        // 所有者信息
        if (merchant.getOwnerUserId() != null) {
            userRepository.findById(merchant.getOwnerUserId()).ifPresent(user -> {
                response.setOwnerUsername(user.getUsername());
                response.setOwnerEmail(user.getEmail());
                response.setOwnerPhone(user.getPhone());
            });
        }
        
        // 统计信息
        response.setStatistics(getMerchantDetailStatistics(merchantId));
        
        // 热门商品（销量前5）
        response.setPopularFoods(getPopularFoods(merchantId, 5));
        
        // 最近订单（最近10条）
        response.setRecentOrders(getRecentOrders(merchantId, 10));
        
        return response;
    }
    
    /**
     * 删除商家
     */
    @Transactional
    public void deleteMerchant(Long merchantId) {
        Optional<Merchant> merchantOpt = merchantRepository.findById(merchantId);
        if (!merchantOpt.isPresent()) {
            throw new RuntimeException("商家不存在");
        }
        
        // 检查未完成订单
        List<String> pendingStatuses = Arrays.asList("pending", "paid", "preparing", "shipping");
        long pendingOrderCount = orderRepository.countByMerchantIdAndStatusIn(merchantId, pendingStatuses);
        if (pendingOrderCount > 0) {
            throw new RuntimeException("该商家有未完成的订单，无法删除");
        }
        
        // 删除商家（级联删除会自动处理关联数据）
        merchantRepository.deleteById(merchantId);
    }
    
    /**
     * 更新商家状态
     */
    @Transactional
    public void updateMerchantStatus(Long merchantId, Integer status) {
        Optional<Merchant> merchantOpt = merchantRepository.findById(merchantId);
        if (!merchantOpt.isPresent()) {
            throw new RuntimeException("商家不存在");
        }
        
        Merchant merchant = merchantOpt.get();
        merchant.setStatus(status);
        merchantRepository.save(merchant);
    }
    
    /**
     * 转换为MerchantItem
     */
    private AdminMerchantListResponse.MerchantItem convertToMerchantItem(Merchant merchant) {
        AdminMerchantListResponse.MerchantItem item = new AdminMerchantListResponse.MerchantItem();
        item.setId(merchant.getId());
        item.setName(merchant.getName());
        item.setDescription(merchant.getDescription());
        item.setLogo(merchant.getLogo());
        item.setPhone(merchant.getPhone());
        item.setAddress(merchant.getAddress());
        item.setBusinessHours(merchant.getBusinessHours());
        item.setMinOrderAmount(merchant.getMinOrderAmount());
        item.setDeliveryFee(merchant.getDeliveryFee());
        item.setRating(merchant.getRating());
        item.setRatingCount(merchant.getRatingCount());
        item.setStatus(merchant.getStatus());
        item.setStatusText(merchant.getStatus() == 1 ? "营业中" : "休息中");
        item.setOwnerUserId(merchant.getOwnerUserId());
        item.setCreatedAt(merchant.getCreatedAt());
        
        // 所有者用户名
        if (merchant.getOwnerUserId() != null) {
            userRepository.findById(merchant.getOwnerUserId()).ifPresent(user -> {
                item.setOwnerUsername(user.getUsername());
            });
        }
        
        // 商品数量
        long foodCount = foodRepository.countByMerchantId(merchant.getId());
        item.setFoodCount(foodCount);
        
        // 订单数量
        long orderCount = orderRepository.countByMerchantId(merchant.getId());
        item.setOrderCount(orderCount);
        
        // 总营收（已送达订单）
        BigDecimal totalRevenue = orderRepository.sumTotalAmountByMerchantIdAndStatus(
            merchant.getId(), 
            "delivered"
        );
        item.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        
        return item;
    }
    
    /**
     * 获取商家统计信息
     */
    private AdminMerchantListResponse.Statistics getMerchantStatistics() {
        AdminMerchantListResponse.Statistics stats = new AdminMerchantListResponse.Statistics();
        
        stats.setTotalMerchants(merchantRepository.count());
        stats.setActiveCount(merchantRepository.countByStatus(1));
        stats.setClosedCount(merchantRepository.countByStatus(0));
        stats.setTotalFoods(foodRepository.count());
        stats.setTotalOrders(orderRepository.count());
        
        // 总营收
        BigDecimal totalRevenue = orderRepository.sumTotalAmountByStatus("delivered");
        stats.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        
        return stats;
    }
    
    /**
     * 获取商家详情统计
     */
    private AdminMerchantDetailResponse.MerchantStatistics getMerchantDetailStatistics(Long merchantId) {
        AdminMerchantDetailResponse.MerchantStatistics stats = 
            new AdminMerchantDetailResponse.MerchantStatistics();
        
        stats.setFoodCount(foodRepository.countByMerchantId(merchantId));
        stats.setActiveFoodCount(foodRepository.countByMerchantIdAndStatus(merchantId, 1));
        stats.setTotalOrders(orderRepository.countByMerchantId(merchantId));
        stats.setPendingOrders(orderRepository.countByMerchantIdAndStatus(merchantId, "paid"));
        
        // 处理中订单（preparing + shipping）
        long preparingCount = orderRepository.countByMerchantIdAndStatus(merchantId, "preparing");
        long shippingCount = orderRepository.countByMerchantIdAndStatus(merchantId, "shipping");
        stats.setProcessingOrders(preparingCount + shippingCount);
        
        stats.setCompletedOrders(orderRepository.countByMerchantIdAndStatus(merchantId, "delivered"));
        
        // 总营收
        BigDecimal totalRevenue = orderRepository.sumTotalAmountByMerchantIdAndStatus(
            merchantId, 
            "delivered"
        );
        stats.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        
        // 平均订单金额
        if (stats.getTotalOrders() > 0) {
            BigDecimal avgAmount = stats.getTotalRevenue()
                .divide(BigDecimal.valueOf(stats.getTotalOrders()), 2, RoundingMode.HALF_UP);
            stats.setAvgOrderAmount(avgAmount);
        } else {
            stats.setAvgOrderAmount(BigDecimal.ZERO);
        }
        
        return stats;
    }
    
    /**
     * 获取热门商品
     */
    private List<AdminMerchantDetailResponse.PopularFood> getPopularFoods(Long merchantId, int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        List<Food> foods = foodRepository.findTopByMerchantIdOrderBySoldCount(merchantId, pageable);
        
        return foods.stream().map(food -> {
            AdminMerchantDetailResponse.PopularFood popularFood = 
                new AdminMerchantDetailResponse.PopularFood();
            popularFood.setId(food.getId());
            popularFood.setName(food.getName());
            popularFood.setImage(food.getImage());
            popularFood.setPrice(food.getPrice());
            popularFood.setSoldCount(food.getSoldCount());
            popularFood.setRating(food.getRating());
            popularFood.setStatus(food.getStatus());
            return popularFood;
        }).collect(Collectors.toList());
    }
    
    /**
     * 获取最近订单
     */
    private List<AdminMerchantDetailResponse.RecentOrder> getRecentOrders(Long merchantId, int limit) {
        Pageable pageable = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "createdAt"));
        List<Order> orders = orderRepository.findByMerchantId(merchantId, pageable);
        
        return orders.stream().map(order -> {
            AdminMerchantDetailResponse.RecentOrder recentOrder = 
                new AdminMerchantDetailResponse.RecentOrder();
            recentOrder.setId(order.getId());
            recentOrder.setOrderNo(order.getOrderNo());
            recentOrder.setTotalAmount(order.getTotalAmount());
            recentOrder.setStatus(order.getStatus());
            recentOrder.setStatusText(getOrderStatusText(order.getStatus()));
            recentOrder.setCreatedAt(order.getCreatedAt());
            
            // 用户名
            userRepository.findById(order.getUserId()).ifPresent(user -> {
                recentOrder.setUsername(user.getUsername());
            });
            
            return recentOrder;
        }).collect(Collectors.toList());
    }
    
    /**
     * 获取订单状态文本
     */
    private String getOrderStatusText(String status) {
        switch (status) {
            case "pending": return "待支付";
            case "paid": return "已支付";
            case "preparing": return "准备中";
            case "shipping": return "配送中";
            case "delivered": return "已送达";
            case "cancelled": return "已取消";
            case "refunded": return "已退款";
            default: return status;
        }
    }
}

